<template>
  <div>
    <!-- 试题录入上传图片的组件，请勿删除!!!!!!!!!! -->
    <el-upload
      class="avatar-uploader"
      :action="$attrs.url || '' "
      :on-success="onSuccess"
      :show-file-list="false"
      :before-upload="beforeAvatarUpload"
      name="file"
      :[httpRequest]="uploadImg"
      @mouseenter.native="isShow= true"
      @mouseleave.native="isShow=false"
    >
      <img v-if="value" class="avatar" :src="value">
      <i v-else class="el-icon-plus avatar-uploader-icon" />
      <div v-show="value && isShow" class="mask" @click.stop>
        <i class="el-icon-zoom-in" @click="handlePreview" />
        <i class="el-icon-delete" @click="handleDelete" />
      </div>
    </el-upload>
    <el-progress v-if="isShowPer" :percentage="percentage" status="warning" style="width:178px;margin-top:10px" :show-text="false" />
    <el-dialog
      title="图片预览"
      :visible.sync="dialogVisible"
    >
      <img :src="value" alt="" style="width:100%">
    </el-dialog>
  </div>
</template>
<script>
import COS from 'cos-js-sdk-v5'
var cos = new COS({
  SecretId: 'AKIDd5NShr02xpYCoHWWJtGOFqCH9l7D3een',
  SecretKey: '71iAQnDbyISM0QxMm12uXwFTgpqjV5e6'
})
export default {
  props: {
    value: {
      type: String,
      default: ''
    }
  },

  data () {
    return {
      isShow: false,
      //   控制dialog弹层的
      dialogVisible: false,
      //   控制进度条的
      isShowPer: false
    }
  },

  computed: {
    httpRequest () {
      return this.$attrs.url ? '' : 'httpRequest'
    }
  },

  methods: {
    uploadImg (params) {
    //   console.log(params)
    // PUT Object 接口请求可以将本地的对象（Object）上传至指定存储桶中
      cos.putObject({
        Bucket: 'xiaochen-1317386150', /* 填入您自己的存储桶，必须字段 */
        Region: 'ap-nanjing', /* 存储桶所在地域，例如ap-beijing，必须字段 */
        Key: params.file.name, /* 存储在桶里的对象键（例如1.jpg，a/b/test.txt），必须字段 */
        Body: params.file, /* 必须，上传文件对象，可以是input[type="file"]标签选择本地文件后得到的file对象 */
        onProgress: function (progressData) {
        //   console.log(JSON.stringify(progressData))
          this.isShowPer = true
          this.percentage = progressData.percent * 100
        }
      }, (err, data) => {
        // console.log(err || data)
        if (err) {
          this.$message.error('上传失败')
        } else {
          const url = 'http://' + data.Location
          this.$emit('input', url)
          console.log(url)
          setTimeout(() => {
            this.isShowPer = false
          }, 500)
        }
      })
    },

    handleDelete () {
      this.$emit('input', '')
    },

    handlePreview () {
      this.dialogVisible = true
    },

    beforeAvatarUpload (file) {
    //   console.log(file)
      const types = ['image/jpeg', 'image/gif', 'image/bmp', 'image/png']
      if (!types.includes(file.type)) {
        this.$message.error('上传图片只能是 JPG、GIF、BMP、PNG 格式!')
        return false
      }
      const maxSize = 5 * 1024 * 1024
      if (file.size > maxSize) {
        this.$message.error('上传的图片大小不能大于5M')
        return false
      }
      return true
    },

    onSuccess (response) {
      console.log(response)
      this.$emit('input', response.url)
    }
  }
}
</script>
<style>
  .avatar-uploader{
    width: 100px;
    height: 80px;
  }
  .mask{
    position: absolute;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.1);
    display: flex;
    align-items: center;
    justify-content: space-around;
  }
  .mask i {
    color: #fff;
    font-size: 28px;
  }
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}
.avatar-uploader .el-upload:hover {
    border-color: #409eff;
}
.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 60px;
    line-height: 60px;
    text-align: center;
}
.avatar {
    width: 100px;
    height: 60px;
    display: block;
}
  </style>
